<template>
<div class=''>
  <el-form
      ref="form"
      :model="form"
      label-width="80px"
    >
      <el-form-item label="用户名">
        <el-input v-model="form.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="form.passWord"></el-input>
      </el-form-item>
      <el-form-item label="验证码">
        <el-input v-model="form.verifyCode"></el-input>
        <div>
          <img v-if="!!imgSrcData" :src="imgSrcData" @click="getVcode"/>
        </div>
      </el-form-item>
      <el-form-item label="记住账号">
          <el-checkbox v-model="rember">记住账号</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitLogin"
        >登录</el-button>
      </el-form-item>
    </el-form>
</div>
</template>

<script>
import API from '@/api/auth'

export default {
  data () {
    return {
      form: {
        userName: '',
        passWord: '',
        verifyCode: ''
      },
      rember: false,
      imgSrcData: ''
    }
  },
  methods: {
    // 登录
    submitLogin () {
      this.$refs.form.validate(valid => {
        if (!valid) return false

        if (this.rember) {
          localStorage.setItem('REMBERUSERNAME', this.form.userName)
          localStorage.setItem('ISREMBER', this.rember)
        } else {
          localStorage.removeItem('REMBERUSERNAME')
          localStorage.removeItem('ISREMBER')
        }

        this.$store.dispatch('Login', this.form)
          .then((userToken) => {
            this.$message.success('登录成功!')
          }).catch(err => {
            this.getVcode()
            this.$$message.error(err.message || '')
          })
      })
    },
    // 获取验证码
    getVcode () {
      API.getVerificationCode().then(res => {
        this.imgSrcData = res
      }).catch(e => {
        this.$message.error(`error:${e.message}`)
      })
    }
  },
  mounted () {
    this.form.userName = localStorage.getItem('REMBERUSERNAME')
    this.rember = JSON.parse(localStorage.getItem('ISREMBER'))
    this.getVcode()
  }
}
</script>
<style lang='less' scoped>
</style>
